import { useEffect, useState, useRef } from 'react';
import { Button, Input, App } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';
import loadable from '@loadable/component';

import { getKeyFromUrl } from '@/utils';
import { addComment } from '@/service/comments';
import useAuthAction from '@/hooks/useAuthAction';
import styles from './index.module.scss';

const IconFont = loadable(() => import('@/components/IconFont'));

export default props => {
    const initState = () => ({
        commentText: '',
        submitting: false,

        id: getKeyFromUrl('id') || '', // 根据需要从props取还是从URL取
    });
    const [state, setState] = useState(initState);
    const { userInfo={} } = useSelector(s => s.common);
    const withAuth = useAuthAction();
    const { commentInfo={}, isReply=false, id } = props;
    const { message } = App.useApp();

    // 评论提交核心逻辑
    const publishCommentCore = async () => {
        let { commentText } = state;

        if(!commentText) return message.warning(`请填写评论`);

        let postData = {
            parentId: commentInfo.id || '',
            content: commentText,
            articleId: state.id,
            toMemberId: commentInfo.fromMemberId || userInfo?.id || '',
        };

        setState(o => ({...o, submitting: true}));
        try{
            const [response, err] = await addComment(postData);
            if(OK_CODE === response?.code) {
                message.success(`评论成功`);
                setState(o => ({...o, commentText: ''}));
                props.onOk();
            }
        }finally{
            setState(o => ({...o, submitting: false}));
        }
    };

    // 带登录检查的评论提交
    const publishComment = withAuth(publishCommentCore);

    useEffect(() => {
        setState(o => ({...o, id}));
    }, [id]);

    return (
        <div className={styles['container']}>
            {
                isReply ?
                    null
                    :
                    <div className={styles['avatar']}>
                        <img src={userInfo?.avatar ? `${userInfo?.avatar}?x-oss-process=image/resize,p_40` : '/images/default-avatar.png'} alt="" />
                    </div>
            }
            <div className={styles['textarea']}>
                <Input.TextArea
                    autoSize={{ minRows: 1, maxRows: 4 }}
                    placeholder={isReply ? `回复${commentInfo?.fromNickName||''}` : '蛐蛐点什么么你~'}
                    value={state.commentText}
                    onChange={e => setState(o => ({...o, commentText:e.target.value}))}
                    // allowClear
                    variant="borderless"
                />
            </div>
            <div className={styles['submit']}>
                <Button loading={state.submitting} onClick={publishComment} type="primary" shape="circle" icon={<IconFont name="icon-send-1"/>}></Button>
            </div>
        </div>
    )
}